onload = function() {


// Imports

var load = rio.load;


// Main code.

// TODO Switch to CodeMirror or at least implement auto-indent.

var env = {
  defs: {log: demoLog},
  // TODO Support also just 'uri1[:;]uri2[:;]...'?
  libs: [{uri: '../examples/'}],
};

$('rioRun').onclick = run;
document.addEventListener('keydown', handleKeyDown, false);
$('sourceArea').value = "# Loading ...\n";
loadInitialContents();


// Functions

function $(id) {
  return document.getElementById(id);
}

// TODO Build a better environment without globals?
// TODO Pass in the env somehow.
function demoLog(text) {
  $('consoleOutput').value += text + "\n";
};

function handleKeyDown(event) {
  if (event.keyCode === 13 && event.ctrlKey) {
    run();
    event.stopPropagation();
  }
}

function loadInitialContents() {
  // TODO Also support prelisting of libs?
  load('../examples/ugly.rio', function(text, uri) {
    $('sourceArea').value = text;
    demoLog("Loaded: " + uri);
  }, function(status, uri) {
    demoLog("Error loading: " + uri);
  });
}

function run() {
  // Clear the console and run.
  // TODO Probably shouldn't clear automatically.

  // TODO Note that we need to have a full list of defined function names
  // TODO and where they are, so we can be prepared for when they get ref'd.
  // TODO Maybe can defer loading and/or full generation until ref, though.
  // TODO Ideally could start background loading the moment we see a ref
  // TODO to let the request run simultaneously with the continued
  // TODO compilation.

  $('consoleOutput').value = "";
  var script = {text: $('sourceArea').value, env: env};
  rio.run(script, function() {
    // Report errors if any.
    // TODO Look for errors across all libs, too. Make env.errors?
    // TODO Put error reporting into common?
    var errors = script.errors;
    for (var e = 0; e < errors.length; e++) {
      var error = errors[e];
      // TODO Better error reporting, including line numbers.
      // TODO This id ref is a hack just for calls!
      demoLog(
        error.type.name + ": " + error.node.id[0].text +
        " at (" + error.pos.join(", ") + ")"
      );
    }
  });
}


};
